﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;

namespace iTool.Utils
{
    public static class iDataConver
    {
        /// <summary>
        /// 实体转列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(string tableName, IList<T> list)
            where T : class, new()
        {
            if (list == null || list.Count <= 0)
                return null;

            DataTable table = new DataTable(tableName);

            bool createColumn = true;

            foreach (T model in list)
            {
                if (model == null)
                    continue;

                var row = table.NewRow();

                foreach (var item in typeof(T).GetProperties())
                {

                    if (item.IsDefined(typeof(NotMappedAttribute), true))
                        continue;

                    if (createColumn)
                        table.Columns.Add(new DataColumn(item.Name, Nullable.GetUnderlyingType(
                                                                    item.PropertyType) ?? item.PropertyType));
                    var value = item.GetValue(model, null) ?? DBNull.Value;

                    row[item.Name] = value;
                }

                if (createColumn)
                    createColumn = false;

                table.Rows.Add(row);
            }

            return table;

        }
    }
}
